<template>
  <tl-sub-page :render="render" :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-dialog" width="1200px" @open="open" @close="close">
    <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="110px" :disabled="disableEditSubmit || disableSave">
      <el-row>
        <el-col :span="24">
          <el-divider content-position="left"><span>1、【项目】相关信息</span></el-divider>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="项目名称">
            <el-input v-model="model.dispprojectid" :disabled="true"> </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目编号">
            <el-input v-model="model.projectcode" :disabled="true"> </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="采购合同金额">
            <el-input-number v-model="model.projectpurchasecontractmoney" controls-position="right" :precision="2" :disabled="true" style="width:95%"> </el-input-number>
            <span>元</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目金额">
            <el-input-number v-model="model.projectmoney" :disabled="true" :precision="2" controls-position="right" style="width:95%"></el-input-number>
            <span>元</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="采购付款金额">
            <el-input-number v-model="model.projectpurchasepaymentmoney" :disabled="true" :precision="2" controls-position="right" style="width:95%"></el-input-number>
            <span>元</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="已回款金额">
            <el-input-number v-model="model.projectrecbillmoney" :disabled="true" :precision="2" controls-position="right" style="width:95%"></el-input-number>
            <span>元</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-divider content-position="left"><span>2、【合同】相关信息</span></el-divider>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="采购合同" prop="purchasecontractid" :required="true" :rules="rules.validateRequire">
            <el-input v-model="model.disppurchasecontractid" :disabled="true" class="tl-ref-selector">
              <el-button slot="append" type="primary" icon="el-icon-search" @click="openpmPurchaseContractRefDialog" v-if="!(disableEditSubmit || disableSave)"></el-button>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="采购合同金额">
            <el-input-number v-model="model.contractmoney" :disabled="true" :precision="2" controls-position="right" style="width:95%"> </el-input-number>
            <span>元</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="已付款金额">
            <el-input-number v-model="model.contracttotalpaymoney" :disabled="true" :precision="2" controls-position="right" style="width:95%"></el-input-number>
            <span>元</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="采购内容">
            <el-input v-model="model.contractcontent" :disabled="true" class="is-disabled"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row>
                <el-col :span="12">
                    <el-form-item label="已付款金额">
                        <el-input-number v-model="model.contracttotalpaymoney" :disabled="true" :precision="2" controls-position="right" style="width:95%"></el-input-number>
                        <span>元</span>
                    </el-form-item>
                </el-col>
            </el-row> -->
      <el-row>
        <el-col :span="24">
          <el-divider content-position="left"><span>3、【付款申请】相关信息</span></el-divider>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="付款部门" prop="purchasedeptcode" :required="true" :rules="rules.validateRequire">
            <tl-ref-dept v-model="model.purchasedeptcode" :initDisplayData.sync="model.purchasedeptname" dataType="code" nameType="fullname" :singleSelect="true" @confirm="onSelectPurchasedept" :externalQueryParam="{ qry_enabled: 1 }"></tl-ref-dept>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="付款组织" prop="purchaseorgname">
            <el-input v-model="model.purchaseorgname" :readonly="true" class="is-disabled"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <!-- <el-col :span="12">
          <el-form-item label="币种" prop="currency" :rules="rules.validateRequire">
            <el-select v-model="model.currency" filterable clearable>
              <el-option v-for="item in codeModel.currencyList" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="申请支付金额" prop="money" :rules="rules.validateRequire">
            <el-input-number v-model="model.money" controls-position="right" :step="1" :min="0" :precision="2" style="width:95%"></el-input-number>
            <span>元</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="付款日期" prop="paydate">
            <el-date-picker v-model="model.paydate" type="date" placeholder="付款日期" value-format="yyyy-MM-dd" disabled></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="费用类型" prop="costtype" :rules="rules.validateRequire">
            <el-select v-model="model.costtype" filterable clearable>
              <el-option v-for="item in codeModel.costtypeList" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="付款方式" prop="paytype" :rules="rules.validateRequire">
            <el-select v-model="model.paytype" filterable clearable>
              <el-option v-for="item in codeModel.paytypeList" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="收款单位" prop="rcvcompany" :rules="rules.validateRequire">
            <el-input v-model="model.rcvcompany"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开户行" prop="openbank" :rules="rules.validateRequire">
            <el-input v-model="model.openbank"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="账号" prop="account" :rules="rules.validateRequire">
            <el-input v-model="model.account"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="付款原因" prop="reason" :rules="rules.validateRequire">
            <el-input v-model="model.reason" type="textarea" :rows="2"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="付款备注" prop="remarks">
            <el-input v-model="model.remarks" type="textarea" :rows="2"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="description">
            <el-input v-model="model.description" type="textarea" :rows="2"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-collapse>
        <el-collapse-item title="【单据】相关信息">
          <el-row>
            <el-col :span="12">
              <el-form-item label="申请公司" prop="orgname">
                <el-input v-model="model.orgname" :readonly="true" class="is-disabled"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请部门" prop="deptname" :required="true" :rules="rules.validateRequire">
                <tl-ref-dept v-model="model.deptcode" :initDisplayData.sync="model.deptname" dataType="code" nameType="fullname" disabled :singleSelect="true" @confirm="onSelectDept" :externalQueryParam="{ qry_enabled: 1 }"></tl-ref-dept>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="申请人姓名" prop="username" :required="true" :rules="rules.validateRequire">
                <tl-ref-user v-model="model.usercode" :initDisplayData.sync="model.username" disabled dataType="code" :singleSelect="true"></tl-ref-user>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请人工号" prop="usercode">
                <el-input v-model="model.usercode" :readonly="true" class="is-disabled"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="单据日期" prop="docdate">
                <el-date-picker v-model="model.docdate" type="date" placeholder="单据日期" value-format="yyyy-MM-dd" :readonly="true" class="is-disabled"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="提交时间" prop="submitdate">
                <el-date-picker v-model="model.submitdate" type="datetime" placeholder="提交日期" value-format="yyyy-MM-dd HH:mm:ss" disabled></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="审批流程" prop="flowid">
                <el-input v-model="model.dispflowid" :readonly="true" class="is-disabled"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="state">
                <el-input v-model="model.dispstate" :readonly="true" class="is-disabled"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-collapse>
    </el-form>
    <tl-approval-history ref="history" sourceType="PmPurchasePayment" :sourceId="model.id" />
    <div slot="footer" class="dialog-footer">
      <el-button :type="disableEditSubmit === false ? 'text' : 'primary'" @click="doCancelEdit" v-if="uiOperateState <= 2">取消</el-button>
      <el-button type="primary" @click="doSubmitEdit" :loading="saveLoading" v-if="!disableEditSubmit" :disabled="disableSave">
        <svg-icon icon-class="save" />保存
      </el-button>
      <tl-attachment ref="attachmentRef" sourceType="PmPurchasePayment" :sourceId="model.id" :disabled="disableAttachmentButton" btnTitle="相关文件"></tl-attachment>
      <!-- <tl-attachment ref="attachmentRef" sourceType="PmPaymentVouchers" :sourceId="model.id" btnTitle="付款单附件" :disabled="disableAttachment" :editable="false"></tl-attachment> -->
      <el-button type="primary" @click="doSubmitApproval" :loading="submitLoading" v-if="!disableEditSubmit" :disabled="disableApproval">
        <svg-icon icon-class="send" />提交审批
      </el-button>
      <el-button type="primary" @click="$refs.history.visible = true" :disabled="disableApprovalHistory">
        <svg-icon icon-class="list" />审批历史
      </el-button>
      <el-button type="primary" @click="doDelApproval" :loading="delApprovalLoading" v-if="!disableEditSubmit" :disabled="disableDelApproval">
        <svg-icon icon-class="undo" />取消审批
      </el-button>
    </div>
    <tlpm-purchase-contract-ref ref="pmPurchaseContractRef" @confirm="getpmPurchaseContractRefData" :isSingleSelect="true" :externalQueryParam="{ qry_state: '9' }"></tlpm-purchase-contract-ref>
  </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_approval_edit } from "@tapui/mixins/mixin_approval_edit"
/** 子组件 */
import tlpmPurchaseContractRef from "@/views/ProjectManage/pmPurchaseContract/refList"
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from "@tapui/utils/http"
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit],
  components: { tlpmPurchaseContractRef },
  data() {
    return {
      moduleTitle: "采购付款申请",
      urlPrefix: "/pm/purchasePayment/",
      disableAttachmentButton: true,
      url: {
        // 额外的url
        getProjectById: "/pm/purchasePayment/getProjectById",
        queryOrgByDeptId: "/pm/resourceArchives/queryOrgByDeptId",
        getContractAndProjectByContractId: "/pm/purchasePayment/getContractAndProjectByContractId"
      }
    }
  },
  props: {
    projectId: {
      type: [Number, String],
      default: function() {
        return ""
      }
    },
    editFlag: {
      type: Boolean,
      default: true
    }
  },
  methods: {
    assignDefaultValue() {
      if (this.isAdd) {
        // if (this.codeModel.flowidList && this.codeModel.flowidList.length > 0) {
        //     this.$set(this.model, 'flowid', parseInt(this.codeModel.flowidList[0].id))
        // }
        // this.$set(this.model, "orgcode", this.org.code)
        // this.$set(this.model, "orgname", this.org.name)
        // this.$set(this.model, "deptcode", this.dept.code)
        // this.$set(this.model, "deptname", this.dept.fullname)
        this.$set(this.model, "usercode", this.user.code)
        this.$set(this.model, "username", this.user.name)
        this.$set(this.model, "docdate", new Date())
      }
    },
    afterDelApproval() {
      this.disableAttachmentButton = false
    },
    loaded() {
      if (this.isAdd === false && this.disableEditSubmit === true) {
        var params = {
          sourceType: 'PmPurchasePayment',
          sourceId: this.model.id
        }
        this.disableAttachmentButton = false
        getAction('/cbo/attachment/calculateCount', params).then((res) => {
          if (res.success) {
            if (res.result === 0) {
              this.disableAttachmentButton = true
              this.$emit('refresh')
            }
          }
        })
      }
      // 页面加载完毕执行
      if (!this.isAdd && this.model.docno) {
        this.title = this.title + `（单据编号：${this.model.docno}）`
      }
    },
    /** 执行新增提交 */
    doAdd() {
      this.saveLoading = true
      // 增加唯一单号
      this.$set(this.model, 'billuid', this.uid)
      postAction(this.url.add, this.model)
        .then(res => {
          if (res.success) {
            this.$tap.message('添加成功', 'success')
            this.queryData(res.result.id)
            this.disableAttachmentButton = false
            this.isAdd = false
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterSubmit()
          this.saveLoading = false
        })
        .catch(err => {
          this.saveLoading = false
        })
    },
    /** 打开采购合同参照 */
    openpmPurchaseContractRefDialog() {
      this.$refs.pmPurchaseContractRef.visible = true
    },
    /** 获取采购合同参数数据 */
    getpmPurchaseContractRefData(selectionRow, selectKey, selectionValue) {
      // 合同相关信息赋值
      this.$set(this.model, "purchasecontractid", selectionRow.id)
      this.$set(this.model, "disppurchasecontractid", selectionRow.contractname)
      this.$set(this.model, "contractmoney", selectionRow.contractmoney)
      this.$set(this.model, "contractcontent", selectionRow.contractcontent)
      this.$set(this.model, "contracttotalpaymoney", selectionRow.totalpaymoney)
      // 采购申请单信息来源于项目 以项目所属部门信息为准
      this.$set(this.model, 'deptcode', selectionRow.deptcode)
      this.$set(this.model, 'deptname', selectionRow.deptname)
      this.$set(this.model, 'orgcode', selectionRow.orgcode)
      this.$set(this.model, 'orgname', selectionRow.orgname)
      const param = {
        projectId: selectionRow.projectid
      }
      getAction(this.url.getProjectById, param).then((res) => {
        if (res.success) {
          const { id, name, code, purchasecontractmoney, projectmoney, purchasepaymentmoney, recbillmoney } = res.result
          this.$set(this.model, "projectid", id)
          this.$set(this.model, "dispprojectid", name)
          this.$set(this.model, "projectcode", code)
          this.$set(this.model, "projectpurchasecontractmoney", purchasecontractmoney)
          this.$set(this.model, "projectmoney", projectmoney)
          this.$set(this.model, "projectpurchasepaymentmoney", purchasepaymentmoney)
          this.$set(this.model, "projectrecbillmoney", recbillmoney)
        } else {
          this.$tap.alert("查询关联项目信息错误，请联系系统管理员")
        }
      })
    },
    onSelectPurchasedept(selectedDepts) {
      const selectedDept = selectedDepts[0]
      const param = {
        deptId: selectedDept.id
      }
      getAction(this.url.queryOrgByDeptId, param).then((res) => {
        if (res.success) {
          const { code: orgCode, name: orgName } = res.result
          this.$set(this.model, "purchaseorgcode", orgCode)
          this.$set(this.model, "purchaseorgname", orgName)
        } else {
          this.$tap.alert("已选部门关联公司信息错误，请联系系统管理员")
        }
      })
    },
    onSelectDept(selectedDepts) {
      const selectedDept = selectedDepts[0]
      const param = {
        deptId: selectedDept.id
      }
      getAction(this.url.queryOrgByDeptId, param).then((res) => {
        if (res.success) {
          const { code: orgCode, name: orgName } = res.result
          this.$set(this.model, "orgcode", orgCode)
          this.$set(this.model, "orgname", orgName)
        } else {
          this.$tap.alert("已选部门关联公司信息错误，请联系系统管理员")
        }
      })
    },
    /** 提交前执行 */
    beforeSubmit() {
      // 申请支付金额 当前采购合同金额 采购合同已付款金额
      const { money, contractmoney, contracttotalpaymoney } = this.model
      if ((money || money === 0) && (contractmoney || contractmoney === 0) && (contracttotalpaymoney || contracttotalpaymoney === 0)) {
        // if (money > contractmoney) {
        //     this.$tap.alert("申请支付金额不能高于采购合同金额", "warning")
        //     return false
        // }
        if (money + contracttotalpaymoney > contractmoney) {
          this.$tap.alert("本次申请支付金额与当前采购合同已付款金额之和不能高于当前采购合同金额！", "warning")
          return false
        }
      }
      // 项目所有采购合同总金额 项目采购总付款金额 项目已回款金额
      // debugger
      const { projectpurchasecontractmoney, projectpurchasepaymentmoney, projectrecbillmoney } = this.model
      if ((money || money === 0) && (projectpurchasecontractmoney || projectpurchasecontractmoney === 0) && (projectpurchasepaymentmoney || projectpurchasepaymentmoney === 0)) {
        if (money + projectpurchasepaymentmoney > projectpurchasecontractmoney) {
          this.$tap.alert("本次申请支付金额与项目采购付款金额之和不能高于项目采购合同金额！", "warning")
          return false
        }
      }
      if ((money || money === 0) && (projectrecbillmoney || projectrecbillmoney === 0) && (projectpurchasepaymentmoney || projectpurchasepaymentmoney === 0)) {
        if (money + projectpurchasepaymentmoney > projectrecbillmoney) {
          this.$tap.alert("本次申请支付金额与项目采购付款金额之和不能高于项目已回款金额！", "warning")
          return false
        }
      }
      return true
    }
  }
}
</script>
